<template>
	<view>

		<!-- 审核状态下，调用壁纸自定义组件 -->
		<template v-if="wxPersonnelWork">
			<ExaminePanel />
		</template>

		<template v-else>

			<view class="container-flex-auto">
				<!-- 顶部内容 -->
				<u-navbar class="navbarRef" bg-color="transparent">
					<template slot="left">
						<u-icon name="arrow-left" size="32rpx" bold="" color="#fff"
							:label="`第${playingVideoData.episode || 1}集`" label-color="#fff" label-size="32rpx"
							@click="topBackHandle()" />
					</template>
					<template slot="center" />
				</u-navbar>

				<!-- 中间视频播放 -->
				<view class="content-flex-auto" :style="{backgroundColor: '#000000'}">
					<swiper :style="{width: `${windowWidth}px`, height: `${100}%`, backgroundColor: '#000000'}"
						:vertical="true" :current="current" :indicator-dots="false" @animationfinish="animationfinish"
						@change="swiperChange">
						<swiper-item v-for="(list,index) in dataList" :key="list.episode">
							<template v-if="k == index">
								<video v-if="isShow" :id="list.episode + '_' + index" :muted="false" :autoplay="true"
									:enable-play-gesture="true" :enable-auto-rotation="true" :controls="true"
									:show-center-play-btn="true" play-btn-position="center" :http-cache="true"
									:custom-cache="false" :show-play-btn="true" :show-fullscreen-btn="false"
									:show-loading="true" :enable-progress-gesture="true" :src="playingVideoData.video"
									:style="{width: `${windowWidth}px`, height: `${videoHeight}px`, marginTop: `${navHeight}px` }"
									@play="play(list.state,$event)" @ended="ended" @progress="progress" />
								<!-- :poster="libraryData.oss_object.url"  -->

								<template v-if="!isShow && shouldConsumeShow">
									<view class="consume-nav">
										<image src="/static/images/player/player-consume-icon.png" />
										<view class="flex ai-center mt-20" @click="coverImageHandle()">
											<text class="font-28 color-fff">哎呀~，金币不足！</text>
											<text class="font-28 main-color">点击充值</text>
										</view>
									</view>
								</template>

								<!-- 要先判断一下dataList[k+1]是否存在，不存在会报video_src未定义的错误 -->
								<!-- 实现下一个视频的预加载 -->
								<!-- <template v-if="dataList[k+1]" style="width: 0px; height: 0px;">
								<video :id="list.episode + '_pre' + index" :muted="true" :autoplay="false"
									:http-cache="true"
									:src="``"
									:style="'width: 0px; height: 0px;'" @progress="progress2" />
							</template> -->
							</template>
						</swiper-item>
					</swiper>

					<!-- 右侧可操作栏 -->
					<view class="use-nav">
						<view class="use-item" @click="likeHandle()">
							<view v-show="playingEpisodeItem.is_like === 1">
								<u-image src="/static/images/player-like-red-icon.png" width="64rpx" height="64rpx">
								</u-image>
							</view>
							<view v-show="playingEpisodeItem.is_like === 0">
								<u-image src="/static/images/player-like-icon.png" width="64rpx" height="64rpx">
								</u-image>
							</view>
							<text>{{ playingEpisodeItem.like_total }}</text>
						</view>
						<view class="use-item" @click="pursuHandle()">
							<view v-show="libraryData.is_pursuing === 1">
								<u-image src="/static/images/player-seek-active-icon.png" width="64rpx" height="64rpx">
								</u-image>
							</view>
							<view v-show="libraryData.is_pursuing === 0">
								<u-image src="/static/images/player-seek-icon.png" width="64rpx" height="64rpx">
								</u-image>
							</view>
							<text>追剧</text>
						</view>
						<view class="use-item">
							<view class="share-btn">
								<u-button open-type="share" text="分享按钮" shape="circle"></u-button>
							</view>
							<u-image src="/static/images/player-wx-icon.png" width="64rpx" height="64rpx"></u-image>
							<text>分享</text>
						</view>
						<view class="use-item" @click="showGroupHandle()">
							<u-image src="/static/images/player-select-icon.png" width="64rpx" height="64rpx"></u-image>
							<text>选集</text>
						</view>
					</view>

				</view>

				<!-- 最底下的文字部分 -->
				<view class="content-nav" @click="showGroupHandle()">
					<view class="flex ai-center">
						<text class="color-fff font-28">《{{ libraryData.title }}》</text>
						<template v-if="isEnd">
							<u-text :text="`已完结${libraryData.total_plot_num}集全 | 选集`" color="#fff" size="28rpx" />
						</template>
						<template v-else>
							<u-text :text="`更新至${libraryData.update_plot_num}集 | 选集`" color="#fff" size="28rpx" />
						</template>
					</view>
					<u-icon name="arrow-up" color="#fff" size="28rpx" />

					<template v-if="showDisablePayIOS">
						<view class="disable-pay-ios">IOS端暂不支持该功能</view>
					</template>
				</view>
			</view>

			<!-- 加入追剧弹出层 -->
			<view class="chase-popup-nav">
				<u-popup :show="chaseModal.show" mode="center" round="24rpx" @close="backHandle()">
					<view class="title">
						<u-icon name="close" size="32rpx" color="#000" @click="backHandle()"></u-icon>
					</view>
					<view class="font-32 main-color font-bold text-center">{{ chaseModal.quit_box_title }}</view>
					<view class="font-color-2 font-28 text-center mt-32 ">{{ chaseModal.quit_box_content }}</view>
					<view class="main-btn">
						<u-button :text="chaseModal.quit_box_btn" type="primary" shape="circle"
							@click="addChaseHandle()"></u-button>
					</view>
				</u-popup>
			</view>

			<!-- 余额支付确认框 -->
			<view class="balance-modal-nav">
				<u-modal :show="balanceModal.show" :z-index="10078" :title="balanceModal.title"
					:content="balanceModal.content" confirm-text="购买" show-cancel-button
					@cancel="balanceModalCancelHandle()" @confirm="balanceModalSubmitHandle()" />
			</view>

			<!-- 选集弹出层 -->
			<PlayerGroup class="recharge-popup-nav" :showGroup.sync="showGroup" :libraryData="libraryData"
				:playerEpisodeNumber="playingEpisodeItem.episode" :allList="allEpisodeList" @resultIndex="resultIndex"
				@needRecharge="needRecharge" @balanceSubmit="balanceSubmit" />

			<!-- 充值弹出层 -->
			<RechargePopup :showPopup.sync="rechargeShow" :video_id="libraryId" :video_name="libraryData.title"
				:episode_id="playingEpisodeItem.episode_id" :episode_number="playingEpisodeItem.episode"
				:episode_price="playingEpisodeItem.episode_price" :shouldContinuePay="true" @success="paySuccess" />

			<!-- 防录屏组件 -->
			<ScreenRecording />

		</template>

	</view>
</template>

<script>
import ExaminePanel from '@/components/examine-panel/examine-panel.vue'
import ScreenRecording from '@/components/screen-recording/screen-recording.vue'
import PlayerGroup from '@/components/player-group/player-group.vue'
import RechargePopup from '@/components/recharge-popup/recharge-popup.vue'

import {
  queryVideoEpisode,
  queryEpisodeInfo,
  videoLikeVery,
  videoLikeCancel,
  videoPursuingVery,
  videoPursuingCancel,
  queryFeaturedList,
} from '@/api/index.js'
import {
  queryUserInfo,
  queryBalance
} from '@/api/user.js'
import storage from '@/utils/storage.js'
import { CHANNEL_ID } from '@/store/mutation-types.js'
import { headerParams } from '@/config/headerParams.js'
import dayjs from 'dayjs'
import duration from 'dayjs/plugin/duration'
dayjs.extend(duration)

export default {
  components: {
    ExaminePanel,
    ScreenRecording,
    PlayerGroup,
    RechargePopup,
  },
  data() {
    return {
      libraryId: '', // 短剧库Id
      libraryData: {
        title: '',
        total_plot_num: '',
        update_plot_num: '',
        is_pursuing: 0,
      }, // 短剧库数据源
      lastEpisodeId: '', // 观看的最后一集集数Id
      allEpisodeList: [], // 所有剧集库
      playingEpisodeItem: {
        is_like: 0,
        like_total: 0,
      }, // 正在播放的剧集库dataList[index]
      playingVideoData: {}, // 正在播放的剧集
      balance: '', // 金币余额
      userInfo: {},
      loadTargetEpisodeId: '', // 加载是，需要跳转的剧集id

      recharge: [], // 充值套餐列表
      isShow: false, // 控制视频是否播放，true播放，false展示封面图
      shouldConsumeShow: false, // 充值背景图
      rechargeShow: false, // 充值套餐弹窗
      windowWidth: 0, // 视频宽度
      videoHeight: 0, // 视频组件高度
      dataList: [], // 播放中的剧集库数据，每10条加载一次
      k: 999, // 当前播放剧集数据的下标
      current: 999, // 和k值一起改，模板的值为0 ，但是为0时进来不会自动播放，所以改成999

      // 选集弹框popup
      showGroup: false,
      navHeight: 64, // 导航栏整体高度

      // 余额支付确认框
      balanceModal: {
        show: false,
        title: '',
        content: '',
        itemData: {},
        allIndex: 0, // 所有剧集库的下标，allEpisodeList[x]
      },

      showDisablePayIOS: false, // IOS端不支持该功能
      wxPersonnelWork: false, // 微信审核人员，直接通过page.json路径访问
      shouldPayIOS: false, // ios系统根据条件判断能否支付, true允许
      iosHistoryList: [], // 临时历史观看集数，用户判断IOS支付
      onloadTime: undefined, // 记录刚进入页面的时间

      // 加入追剧
      chaseModal: {
        show: false,
        quit_box_switch: undefined, // 退出时加入追剧  0-关 1-开
        quit_box_btn: undefined, // 退出时加入追剧-按钮文案
        quit_box_content: undefined, // 退出时加入追剧-弹窗内容
        quit_box_title: undefined, // 退出时加入追剧-弹窗标题
      },

      weekVideoList: []
    }
  },
  computed: {
    // true审核模式
    isAudit() {
      return this.$store.state.appConfig.is_ad == 1
    },
    canPayIOS() {
      return this.$store.state.appConfig.is_ireg == 1
    },
    iosConfigSeriesArr() {
      const {
        ios_r_start_series,
        ios_r_end_series
      } = this.$store.state.appConfig
      const arr = []
      if (ios_r_start_series > 0 && ios_r_end_series > 0) {
        for (let i = ios_r_start_series; i <= ios_r_end_series; i++) {
          arr.push(i)
        }
      }
      // [7,8,9]
      return arr
    },
    iosMinUnlock() {
      return this.$store.state.appConfig.ios_r_min_unlock
    },
    // true已完结
    isEnd() {
      return this.libraryData.is_end == 1
    },
    isIOS() {
      return this.$store.state.systemInfo.osName == 'ios'
    },
    isDefaultChannel() {
      const nowChannelId = storage.get(CHANNEL_ID)
      const defaultChannelId = headerParams.pid
      return nowChannelId == defaultChannelId
    }
  },
  watch: {
    async k(k, old_k) {
      console.log('k=', k, 'old_k=', old_k)
      console.log('swiper正在播放剧集数据源==', this.dataList)

      if (k === 999) return false

      this.isShow = false
      const item = this.dataList[k]

      if (this.iosHistoryList.indexOf(item.episode) === -1) this.iosHistoryList.push(item.episode)
      this.shouldPayIOSFn()

      this.playingEpisodeItem = item
      this.lastEpisodeId = item.episode_id
      this.queryEpisodeInfoFn()

      // swiper正在播放剧集，是最后一集，继续加载剧集数据
      if (k == this.dataList.length - 1) {
        this.loadMoreEpisode(item.episode_id)
      }
    },
  },
  async onLoad(option) {
    // library_id=19&episode_id=740&channel_id=6001
    const {
      library_id,
      episode_id,
      channel_id,
    } = option

    if (!library_id) {
      // 微信审核人员，直接通过page.json路径访问
      this.wxPersonnelWork = true
      return
    }

    this.libraryId = Number(library_id)

    // 之前的渠道Id
    const old_channel_id = storage.get(CHANNEL_ID)
    let new_channel_id = storage.get(CHANNEL_ID)

    if (channel_id) {
      new_channel_id = channel_id
      storage.set(CHANNEL_ID, channel_id)
    }
    if (episode_id) {
      this.loadTargetEpisodeId = episode_id
    }

    this.onloadTime = dayjs()

    /**
			 * 
			 * 注意：以下接口都是await同步执行，顺序不可变换
			 * 
			 * */

    // 判断用户是否登录，未登录则自动登录
    // 这里的登录是解决小程序用户直接转发播放页，此时新用户进入小程序不经过首页登录。
    const token = this.$store.state.token

    if (!token || old_channel_id != new_channel_id) {
      // 未登录或者渠道Id发生变化，请求登录
      await this.getLoginCode()
    }

    // 查用户信息
    await this.queryUserInfoFn()

    // 查用户余额
    await this.queryBalanceFn()

    // 查所有剧集、短剧库详情
    await this.queryAllEpisodeFn()
		
    // 查询本周精选
    await this.queryWeekVideoList()

    // 计算视频高度
    await this.setVideoHight()

    // 计算导航栏高度
    this.setNavHeight()

    // 设置退出时，加入追剧弹框数据源
    this.setQuitingSeekData()

  },
  onShow() {},
  onShareAppMessage() {
    const libraryId = this.libraryId
    const episode_id = this.lastEpisodeId
    const channel_id = storage.get(CHANNEL_ID)

    // 带上短剧库Id、集数、渠道Id进行分享
    return {
      title: this.libraryData.title, // 默认为小程序名称
      path: `/pages/player/player?library_id=${libraryId}&episode_id=${episode_id}&channel_id=${channel_id}`,
      imageUrl: this.libraryData.oss_object.url // 默认为当前页面的截图
    }
  },
  methods: {
    // 登录
    getLoginCode() {
      return new Promise(resolve => {
        uni.login({
          provider: 'weixin',
          success: res => {
            const { code } = res
            // 在store/user.js执行登录请求
            this.$store.dispatch('Login', code).then(res => {
              // 获取小程序配置
              this.$store.dispatch('SetAppConfig')
              resolve(res)
            })
          }
        })
      })
    },

    // 查用户信息
    async queryUserInfoFn() {
      const data = await queryUserInfo()
      this.userInfo = data
    },

    // 查用户余额
    async queryBalanceFn() {
      const data = await queryBalance()
      this.balance = Math.ceil(data.coin)
    },

    // 本周精选数据
    async queryWeekVideoList() {
      const { list } = await queryFeaturedList()
      // 排除掉当前播放的短剧
      this.weekVideoList = list.filter(e => e.id != this.libraryId)
    },

    // 查所有剧集
    async queryAllEpisodeFn() {
      const {
        episode_list,
        library
      } = await queryVideoEpisode({ vid: this.libraryId })
      this.libraryData = library
      this.allEpisodeList = episode_list

      // 直接加载所有剧集，后续再考虑优化
      // this.dataList = this.allEpisodeList

      if (this.loadTargetEpisodeId) {
        // 加载时，有指定跳转到某一集
        const allIndex = this.allEpisodeList.findIndex((item, index) => this.loadTargetEpisodeId == item
          .episode_id)
        this.loadEtcEpisode(allIndex)
      } else if (library.last_episode_id === 0) {
        // 没有观看历史记录，从第1集开始播放
        const allIndex = 0
        this.loadEtcEpisode(allIndex)
      } else {
        // 接口查询到历史记录，从历史记录继续播放
        const allIndex = this.allEpisodeList.findIndex((item, index) => library.last_episode_id == item
          .episode_id)
        if (allIndex !== -1) {
          this.loadEtcEpisode(allIndex)
        } else {
          // 如果后台删除剧集，再添加剧集，剧集id会发生改变，从第1集开始播放
          const allIndex = 0
          this.loadEtcEpisode(allIndex)
        }
      }
    },

    // 查剧集详情信息，未购买会自动购买
    async queryEpisodeInfoFn() {
      queryEpisodeInfo({ episode_id: this.lastEpisodeId }).then(data => {
        const { is_cost } = data
        this.playingVideoData = data

        // 刚刚购买
        if (is_cost === 1) {
          this.dataList[this.k].is_buy = 1
          this.$forceUpdate()
          uni.$u.toast('解锁剧集')
        }

        this.balanceModal = {
          show: false,
          title: '',
          content: '',
          itemData: {},
          allIndex: 0
        }
        this.showGroup = false
        this.showDisablePayIOS = false
        this.isShow = true
        this.shouldConsumeShow = false
        // setTimeout(() => {
        //   // 延迟0.5秒，用户观感更顺滑
        //   this.isShow = true
        // }, 500)
      }).catch(data => {
        uni.$u.toast(data.message)
        this.isShow = false

        console.log(this.shouldPayIOS, '查剧集详情信息，未购买会自动购买')
        if (this.shouldPayIOS === false) {
          this.showDisablePayIOS = true
        } else {
          this.rechargeShow = true
          this.shouldConsumeShow = true
        }
      })
    },

    // 根据配置条件判断，IOS是否可以支付
    shouldPayIOSFn() {
      let result = false
      let round = 0 // 次数
      if (this.isIOS) {
        if (this.canPayIOS && !this.isDefaultChannel) {

          if (this.userInfo.is_pay) {
            // 已付费用户，无需判断
            console.log(this.userInfo.is_pay, '已付费用户')
            result = true
          } else {
            // 配置从7集~9集次数
            this.iosConfigSeriesArr.forEach(configEpisode => {
              const has = this.iosHistoryList.some(historyEpisode => historyEpisode ===
									configEpisode)
              if (has) round++
            })
            // 配置1分钟后
            const nowTime = dayjs()
            const onloadTime = this.onloadTime
            const durationMinutes = dayjs.duration(nowTime.diff(onloadTime)).as('minutes')
            console.info('=======ios支付判断========')
            console.log('次数：', round, '配置数据', this.iosConfigSeriesArr.length)
            console.log('分钟差', durationMinutes, '配置分钟', this.iosMinUnlock)
            const judge_1 = round === this.iosConfigSeriesArr.length
            const judge_2 = durationMinutes > this.iosMinUnlock
            if (judge_1 && judge_2) result = true
          }

        }
      } else {
        result = true
      }
      this.shouldPayIOS = result
      console.log(this.shouldPayIOS, 'IOS是否可以支付？')
    },

    // 选集弹出层返回值
    resultIndex(allIndex) {
      this.isShow = false
      // 因为选集跳转，余额不足时，queryEpisodeInfo接口不会返回data，所以手动设置
      this.playingVideoData.episode = this.allEpisodeList[allIndex].episode
      this.loadEtcEpisode(allIndex)
    },

    balanceModalCancelHandle() {
      this.balanceModal.show = false
    },

    // 余额支付-购买
    balanceModalSubmitHandle() {
      const {
        allIndex,
        itemData
      } = this.balanceModal

      this.balanceModal.show = false
      this.lastEpisodeId = itemData.episode_id
      this.loadEtcEpisode(allIndex)
    },

    // 显示余额支付确认框
    async balanceSubmit(allIndex) {
      // 查用户余额
      await this.queryBalanceFn()

      // allIndex：所有剧集库下标
      const item = this.allEpisodeList[allIndex]
      const { episode_price } = item
      this.balanceModal.show = true
      this.balanceModal.title = '余额：' + this.balance + '金币',
      this.balanceModal.content = `该集为付费内容，需要【${episode_price}金币】购买`
      this.balanceModal.itemData = item
      this.balanceModal.allIndex = allIndex
    },

    // 支付成功
    async paySuccess() {
      await this.queryBalanceFn()
      await this.queryEpisodeInfoFn()

      // 刷新所有剧集数据，避免选集还存在“锁”
      const {
        episode_list,
        library
      } = await queryVideoEpisode({ vid: this.libraryId })
      this.allEpisodeList = episode_list
    },

    needRecharge() {
      if (this.shouldPayIOS === false) return false

      this.rechargeShow = true
    },

    // 计算导航栏高度
    setNavHeight() {
      this.windowWidth = uni.getSystemInfoSync().windowWidth
      // 状态栏高度
      const statusBarHeight = uni.getSystemInfoSync().statusBarHeight
      // #ifdef MP-WEIXIN
      // 获取微信胶囊的位置信息 width,height,top,right,left,bottom
      const custom = uni.getMenuButtonBoundingClientRect()
      // 导航栏高度(标题栏高度) = 胶囊高度 + (顶部距离 - 状态栏高度) * 2
      const navigationBarHeight = custom.height + (custom.top - statusBarHeight - 4) * 2
      // 总体高度 = 状态栏高度 + 导航栏高度
      this.navHeight = navigationBarHeight + statusBarHeight
      // #endif
    },

    // 计算视频高度
    async setVideoHight() {
      // class="content-nav"标签需要接口请求完毕，才渲染才有高度
      const domInfo = uni.createSelectorQuery().in(this).select('.content-nav')
      domInfo.boundingClientRect(data => {
        const { height } = data
        this.videoHeight = uni.getSystemInfoSync().windowHeight - this.navHeight - height
      }).exec()
    },

    // 选集跳转，根据所有剧集的下标allIndex，取下标的前后5条
    loadEtcEpisode(allIndex) {
      const playering = this.allEpisodeList[allIndex]
      let dataArr = []
      if (allIndex < 5) {
        // 直接加载1-10集
        dataArr = this.allEpisodeList.filter((item, index) => index < 10)
      } else {
        // 根据当前播放集，取前后5条
        dataArr = this.allEpisodeList.filter((item, index) => {
          if (index > allIndex - 5 && index < allIndex + 6) return item
        })
      }
      const dIndex = dataArr.findIndex(item => item.episode_id == playering.episode_id)

      // 选集跳转会发生dIndex = this.k的情况，导致k无法触发watch事件
      if (dIndex == this.k) {
        this.current = 999
        this.k = 999
      }

      this.dataList = dataArr
      setTimeout(() => {
        this.current = dIndex
        this.k = dIndex
        console.log('k===', dIndex)
        console.log(dataArr, '=====loadEtcEpisode()取播放剧集下标的前后5条=====')
      }, 0)
    },

    // 加载更多剧集数据，每次加载10条
    loadMoreEpisode(lastEpisodeId) {
      const findIndex = this.allEpisodeList.findIndex(e => lastEpisodeId == e.episode_id)
      const arr = this.allEpisodeList.filter((item, index) => {
        const maxIndex = findIndex + 11
        if (index > findIndex && index < maxIndex) return item
      })
      this.dataList = [...this.dataList, ...arr]
      console.log('loadMoreEpisode()本次加载的剧集====', arr)
    },

    // 打开选集弹出层
    showGroupHandle() {
      this.showGroup = true
    },

    topBackHandle() {
      const isPursuing = this.libraryData.is_pursuing == 1
      const isOpen = this.chaseModal.quit_box_switch == 1
      console.log(this.chaseModal)
      if (isOpen && !isPursuing) {
        this.chasePopupLoop()
      } else {
        this.backHandle()
      }
    },

    // 加入追剧
    addChaseHandle() {
      this.pursuHandle().then(() => {
        setTimeout(() => {
          this.backHandle()
        }, 1000)
      })
    },

    // 返回上一页
    backHandle() {
      try {
        // webview的堆栈
        // eslint-disable-next-line
					const pages = getCurrentPages()
        // 上一级页面
        const pageUp = pages[pages.length - 2]
        const { fullPath } = pageUp.$page
        const tabbar = ['/pages/watching/watching', '/pages/index/index']
        if (tabbar.includes(fullPath)) {
          uni.switchTab({ url: fullPath })
        } else {
          uni.navigateBack()
        }
      } catch (e) {
        uni.switchTab({ url: '/pages/index/index' })
      }
    },

    ended() {
      if (this.k == this.dataList.length - 1) {
        uni.createVideoContext(this.dataList[this.k].episode + '' + this.k, this).seek(0)
        uni.createVideoContext(this.dataList[this.k].episode + '' + this.k, this).pause()
				
        if(this.weekVideoList.length > 0){
          setTimeout(()=> {
					  this.openRandomVideo()
          }, 300)
        } else {
          uni.showModal({
					  content: '已播放完全部剧集',
					  showCancel: false,
					  confirmText: '返回',
					  success(res) {
					    if (res.confirm) {
					      uni.switchTab({ url: '/pages/index/index' })
					    }
					  }
          })
        }
      } else {
        this.current = this.k + 1
      }
    },


    // 点击播放&&暂停
    play(state, event) {
      console.log('点击了播放', state)
    },

    // 封面图点击，剧集未解锁封面图会展示
    async coverImageHandle() {
      this.queryEpisodeInfoFn()
    },

    swiperChange(event) {
      const index = event.detail.current

      // 因为选集跳转，余额不足时，queryEpisodeInfo接口不会返回data，所以手动设置
      this.playingVideoData.episode = this.dataList[index].episode

      this.k = index
      // current一定要改，否则会出现选集黑屏的问题
      this.current = index
    },

    // swiper动画结束时会触发animationfinish事件
    animationfinish(event) {
      // 这里进行判断，如果是最后一个视频就加载视频进入列表
      if (this.k == this.dataList.length - 1) {
        // this.GETNEW()
      }
    },

    // 点赞操作
    async likeHandle() {
      const item = this.dataList[this.k]
      const { episode_id } = item

      // item.is_like: 是否已经喜欢 1-喜欢 0-未喜欢
      // true调用取消接口，false调用添加接口
      const isLike = item.is_like == 1

      if (isLike) {
        await videoLikeCancel({ eid: episode_id })
        item.is_like = 0
        item.like_total--
      } else {
        await videoLikeVery({ eid: episode_id })
        item.is_like = 1
        item.like_total++
      }
      // 根据下标改数组，需要强制通知视图更新，vue2.0缺陷
      this.$forceUpdate()
    },

    // 追剧操作
    async pursuHandle() {
      // is_pursuing: 是否已经追剧 1-追剧 0-未追剧
      // true调用取消接口，false调用添加接口
      const isPursuing = this.libraryData.is_pursuing == 1

      if (isPursuing) {
        await videoPursuingCancel({ vid: this.libraryId })
        this.libraryData.is_pursuing = 0
      } else {
        await videoPursuingVery({ vid: this.libraryId })
        this.libraryData.is_pursuing = 1
      }
    },

    // 视频加载进度
    progress(e) {
      console.log('当前视频加载进度=', e.detail.buffered)
    },

    progress2(e) {
      console.log('预加载视频进度=', e.detail.buffered)
    },

    chasePopupLoop() {
      this.chaseModal.show = !this.chaseModal.show
    },

    // 设置退出时，加入追剧弹框数据源
    setQuitingSeekData() {
      const {
        quit_box_switch,
        quit_box_btn,
        quit_box_content,
        quit_box_title
      } = this.$store.state.appConfig
      Object.assign(this.chaseModal, {
        quit_box_switch,
        quit_box_btn,
        quit_box_content,
        quit_box_title
      })
    },

    // 随机跳转【本周精选】任意一部，不能是当前剧
    openRandomVideo() {
      const arr = this.weekVideoList
      let i = this.weekVideoList.length
      let j, t
      while (i) {
        j = Math.floor(Math.random() * i--)
        t = arr[i]
        arr[i] = arr[j]
        arr[j] = t
      }
      const randomVido = arr[0]
      queryVideoEpisode({ vid: randomVido.id }).then(res=> {
        const { episode_list } = res
        const { episode_id } = episode_list[0]
        console.log('随机排序跳转ID=', arr[0].id)
        uni.redirectTo({ url: `/pages/player/player?library_id=${randomVido.id}&episode_id=${episode_id}` })
      })
     
    },

  }
}
</script>

<style lang="scss" scoped>
	page {
		background-color: #000000;
	}

	.recharge-popup-nav /deep/ .u-fade-enter-to {
		z-index: 10069 !important;
	}

	.recharge-popup-nav /deep/ .u-slide-up-enter-to {
		z-index: 10074 !important;
	}

	.balance-modal-nav /deep/ .u-fade-enter-to {
		z-index: 10075 !important;
	}

	.balance-modal-nav /deep/ .u-slide-up-enter-to {
		z-index: 10076 !important;
	}

	.consume-nav {
		position: absolute;
		top: 0;
		bottom: 0;
		left: 0;
		right: 0;
		margin: auto;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		image {
			width: 260rpx;
			height: 240rpx;
		}
	}

	.use-nav {
		z-index: 999;
		position: absolute;
		bottom: 20%;
		right: 30rpx;
		display: flex;
		flex-direction: column;

		.use-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;
			margin-top: 36rpx;
			position: relative;

			text {
				color: #fff;
				font-size: 24rpx;
			}

			.share-btn {
				width: 100%;
				height: 100%;
				position: absolute;
				left: 0;
				z-index: 2;
				opacity: 0;

				/deep/ .u-button {
					width: 100%;
					height: 100%;
				}
			}
		}
	}

	.content-nav {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 30rpx 30rpx 90rpx 30rpx;
		background-color: #000000;
		position: relative;
	}

	.disable-pay-ios {
		position: absolute;
		top: -44rpx;
		left: 30rpx;
		background-color: $main-color;
		color: #fff;
		font-size: 24rpx;
		padding: 6rpx 10rpx;
		border-radius: 8rpx;
	}

	.chase-popup-nav {
		/deep/ .u-popup__content {
			width: 70%;
		}

		.title {
			display: flex;
			flex-direction: column;
			align-items: flex-end;
			padding: 24rpx 24rpx 20rpx 24rpx;
		}

		.main-btn {
			margin: 36rpx auto 68rpx;
		}

	}
</style>
